package com.tbit.uqbike.client.controller;

import com.tbit.common.constant.OperationPlatform;
import com.tbit.common.entity.UserOpLog;
import com.tbit.uqbike.client.business.user_op_log.service.UserOpLogService;
import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.service.ReturnDepositService;
import com.tbit.uqbike.client.service.TokenService;
import com.tbit.uqbike.client.service.UserService;
import com.tbit.uqbike.client.util.MD5PasswordUtil;
import com.tbit.uqbike.client.util.OutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 押金退还
 *
 * @author Leon
 * 2017年2月24日 下午5:51:05
 */
@Controller
@RequestMapping("/returnDeposit")
public class ReturnDepositController {
    @Autowired
    private ReturnDepositService returnDepositService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserOpLogService userOpLogService;


    /**
     * 申请退还押金管理平台调用
     *
     * @param userId   用户id
     * @param session  会话
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/applyApi")
    public void applyApi(@NotNull(message = "用户id不能为空") Integer userId, @RequestParam(required = false) Integer operatorId, @RequestParam(required = false) String operatorName,
                         @RequestParam(required = false) String operatorPhone, HttpSession session, HttpServletRequest request,
                         HttpServletResponse response, String sign, Long date, String param) {


        boolean result = MD5PasswordUtil.signCheck(sign, date, param);
        if (!result) {
            throw new BaseException("-190002", "签名校验失败");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            User user = userService.getByUserId(userId);
            //用户预约车辆之前提示用户金额是否为负的
            //这里最好查询一下数据库
            User userdb = userService.getByUserId(user.getUserId());
            if (userdb.getMoney() - userdb.getRideMoney() < 0) {
                map.put(ResponseCode.DATA, userdb.getMoney() - userdb.getRideMoney());
                throw new BaseException("-3039", "您的账户已经欠费，请补交欠费金额");
            }
            returnDepositService.apply(user.getAccountId(), user.getUserId(), operatorId, operatorName, operatorPhone);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 申请退还押金
     *
     * @param token    令牌
     * @param session  会话
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/apply")
    public void apply(String token, @RequestParam(required = false) Integer operatorId, @RequestParam(required = false) String operatorName,
                      @RequestParam(required = false) String operatorPhone, HttpSession session, HttpServletRequest request,
                      HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            User user = tokenService.getUser(token);
            //用户预约车辆之前提示用户金额是否为负的
            //这里最好查询一下数据库
            User userdb = userService.getByUserId(user.getUserId());
            if (userdb.getMoney() - userdb.getRideMoney() < 0) {
                map.put(ResponseCode.DATA, userdb.getMoney() - userdb.getRideMoney());
                throw new BaseException("-3039", "您的账户已经欠费，请补交欠费金额");
            }
            userOpLogService.insertSingle(UserOpLog.builder()
                    .accountId(user.getAccountId())
                    .opUser(user.getName())
                    .opUserPhone(user.getPhone())
                    .targetUser(user.getName())
                    .targetUserPhone(user.getPhone())
                    .operation("押金变动")
                    .opType("退押金")
                    .opPlatform(OperationPlatform.CLIENT.code)
                    .opTime(LocalDateTime.now())
                    .result(true)
                    .build());
            returnDepositService.apply(user.getAccountId(), user.getUserId(), operatorId, operatorName, operatorPhone);

            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }
}